const redux = require("redux");


const store = redux.createStore((state = {}) => state);
const actions = {};
const reducers = {};
function registerNameSpace(namespace, initState) {
	reducers[namespace] = (state = initState, actions) => {
		if (actions.type === namespace) {
			return actions.newState;
		} else {
			return state;
		}
	}
	
	store.replaceReducer(redux.combineReducers(reducers));
	
	function registerActions(actionMap) {
		actions[namespace] = {};
		Object.entries(actionMap).forEach(([actionName, method]) => {
			actions[namespace][actionName] = (...rest) => {
				const state = store.getState()[namespace];
				const result = method(state, ...rest);
			}
		})
	}
	function dispatch(state) {
		store.dispatch({type: namespace, newState: state});
	}
	return {
		registerActions,
		dispatch
	}
}


const initState = {
	value: 0
}

const {registerActions, dispatch} = registerNameSpace("table", initState);
registerActions({
	add(state, value) {
		state.value += value;
		dispatch(state);
	}
})

store.subscribe(() => {
	console.log(store.getState());
});



const http = require("node:http");
const server = http.createServer((req, res) => {
	// debugger
	res.statusCode = 200;
	res.end('Hello World\n');
	
	actions.table.add(1);
	
})

server.listen(3000, "127.0.0.1", () => {
	console.log("已启动服务器，监听3000端口");
})

// server.close(() => {
// 	console.log("已关闭服务器");
// });
